const dateToString = require('../utils').dateToString;
const _ = require('lodash');

module.exports = app => {

  class Class extends app.Service {

    /** 给所有爬虫下发配置 */
    sendConfig(data) {
      this.app.io.emit('config', data);
    }

    /** 随机给一个爬虫发送任务 */
    randomSendTask(task) {
      const keys = Object.keys(this.app.io.sockets.sockets);
      if (keys.length === 0)
        return;
      const key = keys[Math.floor(Math.random() * keys.length)];
      // console.log('random', key);
      this.app.io.sockets.sockets[key].emit('task', task);
    }

    async saveData(room) {
      const now = new Date();

      const key = 'a_d:' + dateToString(now);
      const field = room.platform.id + '_' + room.anchor.room;

      //获取直播分类
      let [roomData] = await Promise.all([

        //获取redis缓存
        this.app.redis.hget(key, field),

        //计算直播时长，不返回数据
        this.getRedisLiveTime(room, now),

      ]);
      const type = room.type;

      if (roomData) {
        room = JSON.parse(roomData);
      }
      else {
        room.type = [];
      }

      if (type) {
        if (type.id)
          room.type.push(type.id);
        else
          room.type.push(type);
      }
      else //没有直播类型
        room.type.push(1);//默认类型

      this.app.redis.hset(key, field, JSON.stringify(room));
    }

    /**
     *
     * 计算开播时间，单位 分钟
     * @param room
     * @param date {Date}
     * @returns {Promise<number>}
     */
    async getRedisLiveTime(room, date) {
      const today = dateToString(date);
      const redisKey = room.platform.id + ':' + today + ':' + room.anchor.room;

      //读取redis缓存，拿出
      let lastTimestamp = await this.app.redis.get(redisKey);

      const now = date.getTime();

      if (!room.data.hasOwnProperty('num_live'))
        room.data.num_live = 0;

      if (lastTimestamp) {
        room.data.num_live += Math.floor((now - parseInt(lastTimestamp)) / 6e4);
      }

      //保存缓存，10分钟过期
      this.app.redis.set(redisKey, now, 'EX', 10 * 60);
    }
  }

  return Class;
};